package com.jackrain.nea.ext.sequence.observer;

import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.ext.sequence.util.SequenceGenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;

/**
 * @author xubin
 * 2017-11-18
 */
@Slf4j
public class SequenceObserver implements Observer {

    private String sequenceName;
    private JSONObject object;
    private Long id;
    private Class[] extendTypes;
    private Object[] extendParams;
    private Locale locale;
    private Boolean istTest;
    private Object mapperBean;
    private String methodName;



    public SequenceObserver(SequenceExec subject, String sequenceName, JSONObject object, Long id,Class[] extendTypes,Object[] extendParams,Object mapperBean,String methodName, Locale locale, boolean isTest) {
        this.sequenceName = sequenceName;
        this.object = object;
        this.mapperBean = mapperBean;
        this.id = id;
        this.extendTypes = extendTypes;
        this.extendParams = extendParams;
        this.locale = locale;
        this.istTest = isTest;
        this.methodName=methodName;
        subject.addObserver(this);
    }


    @Override
    public void update(Observable o, Object arg) {
        String sequenceNumber = SequenceGenUtil.generateSquence(this.sequenceName, this.object, this.locale, this.istTest);

        Class[] paramTypes ={String.class,Long.class};
        Object[] params = {sequenceNumber,id};
        try {
            mapperBean.getClass().getDeclaredMethod(methodName, ArrayUtils.addAll(paramTypes,extendTypes)).invoke(mapperBean,ArrayUtils.addAll(params,extendParams));
        } catch (IllegalAccessException|InvocationTargetException|NoSuchMethodException e) {
            log.error(e.getMessage(),e);
            throw new NDSException("不支持的方法或错误的参数,"+e.getMessage(),e);
        }
    }
}
